package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicineinventoryEmployeeExtEntity;
import city.spring.modules.medicine.repository.MedicineinventoryEmployeeExtRepository;
import city.spring.modules.medicine.service.MedicineinventoryEmployeeExtService;
import city.spring.modules.medicine.vo.MedicineinventoryUserVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：药品盘点与盘点人员关系
 *
 * @author 谢金婷
 * @date 2020-07-27 09:44:54
 */
@RestController
@RequestMapping("/medicineinventory/{inventoryId}/employee")
public class MedicineinventoryEmployeeExtController extends ApiController {
    private final MedicineinventoryEmployeeExtService medicineinventoryEmployeeExtService;
    private final MedicineinventoryEmployeeExtRepository medicineinventoryEmployeeExtRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicineinventoryEmployeeExtEntity, ?>> entityOrderFields;

    public MedicineinventoryEmployeeExtController(MedicineinventoryEmployeeExtService medicineinventoryEmployeeExtService, MedicineinventoryEmployeeExtRepository medicineinventoryEmployeeExtRepository) {
        this.medicineinventoryEmployeeExtService = medicineinventoryEmployeeExtService;
        this.medicineinventoryEmployeeExtRepository = medicineinventoryEmployeeExtRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicineinventoryEmployeeExtEntity::getId);
        entityOrderFields.add(MedicineinventoryEmployeeExtEntity::getMedicineinventoryId);
        entityOrderFields.add(MedicineinventoryEmployeeExtEntity::getUserId);
    }

    @ModelAttribute
    public void getInventoryId(@PathVariable String inventoryId) {
        if (inventoryId == null) {
            throw new RuntimeException("盘点计划ID必须不为空");
        }
    }

    /**
     * 获取全部的 <strong>药品盘点与盘点人员关系</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicineinventoryEmployeeExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryEmployeeExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

//    /**
//     * 分页获取 <strong>药品盘点与盘点人员关系</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MedicineinventoryEmployeeExtEntity entity) {
//        LambdaQueryChainWrapper<MedicineinventoryEmployeeExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicineinventoryEmployeeExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取盘点计划所有人员列表
     *
     * @param inventoryId 盘点计划ID
     */
    @GetMapping
    public Object list(@PathVariable String inventoryId) {
        return success(medicineinventoryEmployeeExtRepository.getInventoryUsers(inventoryId));
    }

//    /**
//     * 获取一个 <strong>药品盘点与盘点人员关系</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(medicineinventoryEmployeeExtService.getById(id));
//    }

    /**
     * 获取方案的一个人员信息
     *
     * @param inventoryId 方案ID
     * @param extId       关联ID
     * @return
     */
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String inventoryId, @PathVariable Long extId) {
        return success(medicineinventoryEmployeeExtRepository.getInventoryUser(inventoryId, extId));
    }


//    /**
//     * 添加一个 <strong>药品盘点与盘点人员关系</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody MedicineinventoryEmployeeExtEntity entity) {
//        medicineinventoryEmployeeExtService.saveMedicineinventoryEmployeeExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }

    /**
     * 给方案添加多个人员信息
     *
     * @param inventoryId 方案ID
     * @param users       所添加的人员信息列表
     * @return
     */
    @PostMapping
    public Object addAll(@PathVariable String inventoryId, @RequestBody List<MedicineinventoryEmployeeExtEntity> users) {
        // 查出已有的数据
        List<MedicineinventoryUserVO> dbUsers = medicineinventoryEmployeeExtRepository.getInventoryUsers(inventoryId);
        // 数据库已经存在的班次列表
        Set<String> dbUserIdsSet = dbUsers.stream()
                .map(MedicineinventoryEmployeeExtEntity::getUserId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MedicineinventoryEmployeeExtEntity> needSaveUsers = users.stream()
                .filter(item -> {
                    item.setMedicineinventoryId(inventoryId);
                    String userId = item.getUserId();
                    // 过滤出不存在数据库中的数据
                    return userId != null && !dbUserIdsSet.contains(userId);
                }).collect(Collectors.toList());
        if (!needSaveUsers.isEmpty()) {
            medicineinventoryEmployeeExtService.saveBatch(needSaveUsers);
        }

        return success(null);
    }

//    /**
//     * 修改一个 <strong>药品盘点与盘点人员关系</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MedicineinventoryEmployeeExtEntity entity) {
//        entity.setId(id);
//        medicineinventoryEmployeeExtService.updateMedicineinventoryEmployeeExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }

    /**
     * 修改一个方案关联的人员信息
     *
     * @param inventoryId 方案ID
     * @param extId       关联ID
     * @param extEntity   接收的数据
     * @return
     */
    @PutMapping("{extId}")
    public Object update(@PathVariable String inventoryId, @PathVariable Long extId, @RequestBody MedicineinventoryEmployeeExtEntity extEntity) {
        extEntity.setId(String.valueOf(extId));
        extEntity.setMedicineinventoryId(inventoryId);
        medicineinventoryEmployeeExtService.updateMedicineinventoryEmployeeExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>药品盘点与盘点人员关系</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicineinventoryEmployeeExtService.deleteMedicineinventoryEmployeeExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品盘点与盘点人员关系</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicineinventoryEmployeeExtService.deleteMedicineinventoryEmployeeExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicineinventoryEmployeeExtEntity> buildLambdaQuery(MedicineinventoryEmployeeExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryEmployeeExtEntity> lambdaQuery = medicineinventoryEmployeeExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicineinventoryEmployeeExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), MedicineinventoryEmployeeExtEntity::getMedicineinventoryId, entity.getMedicineinventoryId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUserId()), MedicineinventoryEmployeeExtEntity::getUserId, entity.getUserId());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicineinventoryEmployeeExtEntity> buildQuery(MedicineinventoryEmployeeExtEntity entity) {
        QueryWrapper<MedicineinventoryEmployeeExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), "medicineinventory_id", entity.getMedicineinventoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "user_id", entity.getUserId());
        return wrapper;
    }

}
